﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iLangl.Model;

namespace iLangl.BusinessModel.Managers
{
	public class SettingsManager : BaseManager
	{
		#region Singelton Pattern
		private SettingsManager()
		{
		}

		private static SettingsManager instance;
		private static object mutex = new object();
		/// <summary>
		/// The instance of the SettingsManager.
		/// </summary>
		public static SettingsManager Instance
		{
			get
			{
				if (instance == null)
				{
					lock (mutex)
					{
						if (instance == null)
						{
							instance = new SettingsManager();
						}
					}
				}
				return instance;
			}
		}
		#endregion

		public void UpdateTPSettings(PluginLicense license, SettingsFromTP settings)
		{
			List<PluginLanguage> pluginLanguages = new List<PluginLanguage>();

			foreach (Language language in settings.Languages)
			{
				PluginLanguage planguage = new PluginLanguage();
				planguage.PluginCode = language.LanguageId;
				planguage.PluginName = language.LanguageName;
				planguage.PluginId = license.Plugin.ID;

				Language lang = LanguageManager.Instance.FindLanguageByName(language.LanguageName);

				planguage.LanguageId = lang.LanguageId;
				planguage.LanguageName = lang.LanguageName;
				
				pluginLanguages.Add(planguage);
			}

			LanguageManager.Instance.RegisterPluginLanguages(pluginLanguages);


			List<TPWorkArea> workareaList = new List<TPWorkArea>();

			foreach (WorkArea workarea in settings.WorkAreas)
			{
				TPWorkArea tpworkarea = new TPWorkArea();
				tpworkarea.Id = workarea.Id;
				tpworkarea.Name = workarea.Name;
				tpworkarea.TpId = license.Contact.Company.Id;
				tpworkarea.TPWorkAreaId = workarea.Id;
				tpworkarea.TPWorkAreaName = workarea.Name;
				tpworkarea.ParentId = workarea.ParentId;

				workareaList.Add(tpworkarea);
			}

			WorkAreaManager.Instance.RegisterTPWorkAreas(workareaList);


			List<TPProduct> productList = new List<TPProduct>();

			foreach (Product product in settings.Products)
			{
				TPProduct tpproduct = new TPProduct();

				tpproduct.Id = product.Id;
				tpproduct.Name = product.Name;
				tpproduct.Description = product.Description;
				tpproduct.TpId = license.Contact.Company.Id;
				tpproduct.TPProductDescription = product.Description;
				tpproduct.TPProductId = product.Id;
				tpproduct.TPProductName = product.Name;

				productList.Add(tpproduct);
			}

			ProductManager.Instance.RegisterTPProducts(productList);
			
		}
	}
}
